﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.CRUDSqlAzure.Phone.Pages
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Navigation;
    using Microsoft.Phone.Controls;
    using Microsoft.Samples.CRUDSqlAzure.Phone.Helpers;
    using Microsoft.Samples.CRUDSqlAzure.Phone.Models;
    using Microsoft.Samples.CRUDSqlAzure.Phone.ViewModel;
    using System.Windows.Media.Imaging;
    using Microsoft.Phone.Tasks;
    using Microsoft.Phone;
    

    public partial class ReportAddPage : PhoneApplicationPage
    {
        public ReportAddPage()
        {
            this.InitializeComponent();

            this.ViewModel = new ReportDetailsPageViewModel();
            this.ViewModel.SaveChangesSuccess += (s, e) => this.NavigationService.GoBack();
        }

        public ReportDetailsPageViewModel ViewModel
        {
            get { return this.DataContext as ReportDetailsPageViewModel; }
            set { this.DataContext = value; }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {           
            //this.ViewModel.Report == null            

            var report = PhoneHelpers.GetApplicationState<Report>("CurrentReportRow");
            this.ViewModel.SetReportModel(report);
            PhoneHelpers.RemoveApplicationState("CurrentReportRow");            
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.ViewModel.DetachReportModel();
        }

        private void OnDeleteReport(object sender, EventArgs e)
        {
            this.ViewModel.DeleteReport();
        }

        private void OnSaveReport(object sender, EventArgs e)
        {
            var focusTextbox = FocusManager.GetFocusedElement() as TextBox;
            if (focusTextbox != null)
            {
                var binding = focusTextbox.GetBindingExpression(TextBox.TextProperty);
                binding.UpdateSource();
            }

            this.ViewModel.SaveReport();
        }
        
        private void OnTakePhoto(object sender, EventArgs e)
        {
            //The camera chooser used to capture a picture.
            CameraCaptureTask ctask;

            //Create new instance of CameraCaptureClass
            ctask = new CameraCaptureTask();
            
            //Create new event handler for capturing a photo
            ctask.Completed += new EventHandler<PhotoResult>(ctask_Completed);

            //Show the camera.
            ctask.Show();

            
        }

        /// <summary>
        /// Event handler for retrieving the JPEG photo stream.
        /// Also to for decoding JPEG stream into a writeable bitmap and displaying.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ctask_Completed(object sender, PhotoResult e)
        {

            if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null)
            {
                

                //Convert the photo to bytes
                Byte[] PhotoBytes = new byte[e.ChosenPhoto.Length];

                // rewind first
                var lastpos = e.ChosenPhoto.Position;
                e.ChosenPhoto.Position = 0;

                // read stream into byte array
                e.ChosenPhoto.Read(PhotoBytes, 0, PhotoBytes.Length);
                // Save into the new report
                this.ViewModel.Report.Photo = PhotoBytes;
                

                //ReportImage.GetBindingExpression(Image.SourceProperty).UpdateSource();

                //Populate image control with WriteableBitmap object.                
                e.ChosenPhoto.Position = lastpos;
                WriteableBitmap CapturedImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                ReportImage.Source = CapturedImage;
                Camera.Visibility = Visibility.Visible;
               

            }
            else
            {
                //user decided not to take a picture
            }
        }
        

        private void OnNavigatePage(object sender, NavigationEventArgs e)
        {
            this.NavigationService.Navigate(e.Uri);
        }
    }
}